package com.qf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 检测请求时间是否超过指定阀值
 */

@Component
public class TimestampFilter extends ZuulFilter {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String timestamp = request.getParameter("timestamp");

        try {
            Date parse = simpleDateFormat.parse(timestamp);
            Date date = new Date();
            long sub = date.getTime()-parse.getTime();
            if (sub<0||sub>60000){
                currentContext.setSendZuulResponse(false);
                currentContext.setResponseBody("访问时间超时！请重试");
                currentContext.getResponse().setContentType("text/html;charset=utf-8");
            }
        } catch (ParseException e) {
            e.printStackTrace();
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseBody("时间格式错误！！");
            currentContext.getResponse().setContentType("text/html;charset=utf-8");
        }


        return null;
    }
}
